#include "scanner.h"

const char *scanner::magic_label = "NIalias";

scanner::scanner(int listener_port, int teller_port, ContactListManager *contactlistmanager,
                 int initial_mode, QString alias)
{
    this->udp_socket.bind(teller_port, QUdpSocket::ShareAddress);
    this->mode = initial_mode;
    this->time_since_last_broadcast = ContactListManager::broadcast_maxtime;
    this->listener_port = listener_port;
    this->teller_port = teller_port;
    this->contactlistmanager = contactlistmanager;
    this->alias = alias;
    this->update();
}

void scanner::broadcastyourself()
{
    QString temporal_string = this->alias;
    temporal_string.append(magic_label);
    temporal_string = QString::QString("I").append(temporal_string);
    temporal_string = QString::number(this->listener_port).append(temporal_string);
    QByteArray temporal_array = temporal_string.toUtf8();
    this->udp_socket.writeDatagram(temporal_array, temporal_array.size(),
                                   QHostAddress::Broadcast, this->teller_port);
    this->time_since_last_broadcast = 0;
}

void scanner::update()
{
    if (this->mode == scanner::public_mode)
    {
        if (this->time_since_last_broadcast >= ContactListManager::broadcast_mintime)
            broadcastyourself();
    }
    while (this->udp_socket.hasPendingDatagrams())
    {
        QByteArray temporal_array = QByteArray::QByteArray(this->udp_socket.pendingDatagramSize(), ' ');
        QHostAddress temporal_address;
        int temporal_port;
        this->udp_socket.readDatagram((char *)temporal_array.data(),
                                      temporal_array.size(), &temporal_address, 0);
        QString temporal_string = QString::fromUtf8(temporal_array);
        if (temporal_string.endsWith(magic_label)) {
            // It's a netim alias
            temporal_string = temporal_string.left(temporal_string.length() - (QString::QString(magic_label)).length());
            temporal_port = temporal_string.left(temporal_string.indexOf(QChar('I'))).toInt();
            temporal_string = temporal_string.right(temporal_string.length() - (temporal_string.indexOf(QChar('I')) + 1));
            if ((temporal_string != this->alias) && (temporal_port > 0)) {
                this->contactlistmanager->newPublicIdentityPacket(temporal_string,
                             temporal_port, temporal_address);
            }
        }
    }
    if (time_since_last_broadcast < ContactListManager::broadcast_maxtime) time_since_last_broadcast++;
    if (time_online > 0) this->contactlistmanager->officialy_online = true;
    else this->contactlistmanager->officialy_online = false;
    if (mode == 2) time_online++;
    else time_online = 0;
    this->contactlistmanager->endOfBroadcastScan();
    this->contactlistmanager->updateUi();
}

void scanner::switchmode(int mode)
{
    this->mode = mode;
}
